<?php
/**
 * CreateTime: 2023/11/24 15:17
 * User:LinQ
 */

namespace App\Http\Service\Company;

use App\Func\System\OperateLogFunc;
use App\Func\User\UserFunc;
use App\Http\Service\BasicInterfaceService;
use App\Http\Service\BasicService;
use App\Models\CompanyDepartment\CompanyModel;
use App\Models\CompanyDepartment\DepartmentModel;
use App\Models\Users\UsersModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Symfony\Component\Uid\UuidV4;

class CompanyService implements BasicInterfaceService
{
    public function getList(array $prams)
    {
        $page_size = $prams['page_size'] ?? 10;
        $filters = $prams['filters'] ?? [];
        $desc = $prams['desc'] ?? [];
        $companyModel = new CompanyModel();
        if($filters){
            $this->listSelectFilters($companyModel,$filters);
        }
        $res = $companyModel->cList($companyModel,$page_size,$desc);
        // 处理数据
        $res['data'] = $this->dispose($res['data']);
        s_c_return($res,trans('message.get_list_ok',[
            'name' => trans('key.company')
        ]));
    }

    public function getSelectHasPage($prams)
    {
        $page_size = $prams['page_size'] ?? 10;
        $filters = $prams['filters'] ?? [];
        $desc = $prams['desc'] ?? [];
        $companyModel = (new CompanyModel());
        if($filters){
            $this->listSelectFilters($companyModel,$filters);
        }
        $res = $companyModel->cList($companyModel,$page_size,$desc,[
            'company_name as value'
        ]);
        // 处理数据
        $res['data'] = $this->dispose($res['data']);
        s_c_return($res,trans('message.get_list_ok',[
            'name' => trans('key.company')
        ]));
    }

    public function listSelectFilters($query, $filters)
    {
        $filters = trim_array($filters);
        if(map_has_value($filters,'company_name')){
            $query->pushFilter('company_name',$filters['company_name'],'like');
        }
        if(map_has_value($filters,'company_code')){
            $query->pushFilter('company_code',$filters['company_code'],'like');
        }
    }

    public function getSelect()
    {
        $companyModel = new CompanyModel();
        $res = $companyModel->select([
           'company_id as key',
           'company_name as value'
        ])->get();
        s_c_return($res,trans('message.get_list_ok',[
            'name' => trans('key.company')
        ]));
    }

    public function getInfo($id)
    {
        $companyModel = new CompanyModel();
        $res = $companyModel->with(["departments" => function($query){
            $query->select([
                "*",
                "owner_id as owner_str",
                "responsible_user_id as responsible_user_str"
            ]);
        }])->where('company_id',$id)->get();
        s_c_return($res,trans('message.get_detail_ok',[
            'name' => trans('key.company')
        ]));
    }

    public function create($data)
    {
       $companyModel = new CompanyModel();
       DB::beginTransaction();
        try {
            // 设置默认数据
            $companyUuid = (\Symfony\Component\Uid\UuidV4::v6()->toRfc4122());
            $companyId = $companyModel->insertGetId([
                'company_name' => $data['company_name'],
                'company_code' => $data['company_code'],
                'company_union_id' => $companyUuid,
                'created_at' => date("Y-m-d h:i:s"),
                'updated_at' => date("Y-m-d h:i:s"),
            ]);
            // 自动为当前公司创建一个部门和用户作为一级部门
            $departmentModel = new DepartmentModel();
            $departmentId = $departmentModel->insertGetId([
                'com_id' => $companyId,
                'department_name' => $data['company_name'],
                'pid' => 0,
                'responsible_user_id' => 0,
                'owner_id' => -1,
                'status' => 1,
                'created_at' => date("Y-m-d h:i:s"),
                'updated_at' => date("Y-m-d h:i:s"),
            ]);
            $usersModel = new UsersModel();
            $puPvKey = rsa_pu_pv_key();
            $userId = $usersModel->insertGetId([
                'name' => 'admin',
                'com_id' => $companyId,
                'account' => 'admin',
                'email' => Str::random(10).'@gmail.com',
                'phone' => Str::random(11),
                'password' => (new UserFunc())->getHashPassByUser('admin'),
                'union_id' => UuidV4::v6()->toRfc4122(),
                'enable_status' => 1,
                'status' => 1,
                'pu_key' => $puPvKey['pu_key'],
                'pv_key' => $puPvKey['pv_key'],
                'created_at' => date("Y-m-d h:i:s"),
                'updated_at' => date("Y-m-d h:i:s"),
            ]);
            // 添加部门到用户
            DB::table('department_user')->insert(
                [
                    'department_id' => $departmentId,
                    'user_id' => $userId,
                    'created_at' => date("Y-m-d h:i:s"),
                    'updated_at' => date("Y-m-d h:i:s"),
                ]
            );
            // 修改部门的经办人到部门
            $departmentModel->where('department_id',$departmentId)->update([
                'responsible_user_id' => $userId
            ]);
            // 添加操作记录
            OperateLogFunc::addOperate(
                'CompanyService',$companyId,'create');
            DB::commit();
            s_c_return(['company_id'=>$companyId],trans('message.created_ok',[
                'name' => trans('key.company')
            ]));
        }catch (\Exception $exception){
            DB::rollBack();
            s_fail_return(null,trans('message.created_err',[
                'name' => trans('key.company')
            ]));
        }
    }

    public function fakeDelete($id)
    {

    }

    public function delete($data)
    {

    }

    public function update($data)
    {
        $company_id = $data['company_id'] ?? 0;
        $companyModel = new CompanyModel();
        try {
            $res = $companyModel->where('company_id',$company_id)->update($data);
            if($res){
                // 添加操作记录
                OperateLogFunc::addOperate(
                    'CompanyService',$res,'update'
                );
              s_c_return(null,trans('message.update_ok',[
                  'name' => trans('key.company')
              ]));
            }
            s_fail_return(null,trans('message.update_err',[
                'name' => trans('key.company')
            ]));
        }catch (\Exception $exception){
            s_fail_return(null,trans('message.update_err',[
                'name' => trans('key.company')
            ]));
        }

    }

    public function dispose($data): mixed
    {
        return $data;
    }


    public function fakeDeleteByIds($ids)
    {
        
    }
}